package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ComicTimeContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.ComicCourierPagerAdapter
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ComicModel
import fm.dongman.presenterlib.presenter.ComicTimePresenter
import kotlinx.android.synthetic.main.fragment_comic_time.*
import kotlinx.android.synthetic.main.item_comic_time.view.*
import org.jetbrains.anko.onClick


/**
 * 动漫番剧时间页面
 * Created by Administrator on 2017/10/24.
 */
class ComicTimeFragment : BaseFragment(), ComicTimeContract.IComicTimeView {
    private lateinit var mPresenter: ComicTimeContract.IComicTimePresenter // 数据控制器
    private var mRecyclerView: ArrayList<RecyclerView> = ArrayList()  // 番剧时间 recyclerView
    private lateinit var mWeekdays: List<Map<String, String>> // 一周的7个星期

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater?.inflate(R.layout.fragment_comic_time, container, false)
        ComicTimePresenter(this, Injection.provideComicTimeRepository())
        return fragment!!
    }

    override fun initData() {
        onStateChanged(MultiStateLayout.LOADING)
        mPresenter.startLoad()
    }

    override fun bindData() {
        bindToolbar()
        bindPage()
    }

    /**
     * 绑定 toolbar
     */
    private fun bindToolbar() {
        //设置Toolbar padding
        mComicTimeToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mComicTimeToolbar.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
    }

    /**
     * 绑定 page
     */
    private fun bindPage() {
        mVpComicTime.offscreenPageLimit = 2
        mVpComicTime.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                onStateChanged(MultiStateLayout.LOADING)
                mPresenter.getWeekDayComics(mWeekdays[position].keys.first())
            }
        })
    }

    override fun setPresenter(presenter: ComicTimeContract.IComicTimePresenter) {
        mPresenter = presenter
    }

    override fun isActive(): Boolean {
        return isAdded
    }

    override fun getViewContext(): Context {
        return activity
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError("动漫番剧时间页面加载失败！")
    }

    override fun showWeekDays(weekdays: List<Map<String, String>>) {
        mRecyclerView.clear()
        mComicTimeTab.removeAllTabs()
        mWeekdays = weekdays
        weekdays.forEach {
            mRecyclerView.add(RecyclerView(activity))
            mComicTimeTab.addTab(mComicTimeTab.newTab().setText(it.values.first()))
        }
        mVpComicTime.adapter = ComicCourierPagerAdapter(activity, weekdays.map { it.values.first() }, mRecyclerView)
        mComicTimeTab.setupWithViewPager(mVpComicTime)
        // 先加载第一个页面数据
        mPresenter.getWeekDayComics(mWeekdays[0].keys.first())
    }

    override fun showLoadComicsFailed() {
        Toast.makeText(activity, "动漫列表加载失败！", Toast.LENGTH_LONG).show()
    }

    override fun showComicList(comics: List<IModel.IComicModel>, weekday: String) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mRecyclerView[mWeekdays.map { it.keys.first() }.indexOf(weekday)].adapter =
                ComicTimeAdapter(activity, comics)
    }

    /**
     * 修改状态
     * @param state 状态
     */
    private fun onStateChanged(state: Int) {
        mTimeMultiStateLayout.changeState(state)
    }

    companion object {
        fun getInstance(): ComicTimeFragment {
            return ComicTimeFragment()
        }
    }

    /**
     * 时间表项适配器
     */
    private class ComicTimeAdapter constructor(private val mContext: Context, private val mData: List<IModel.IComicModel>)
        : RecyclerView.Adapter<ComicTimeViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ComicTimeViewHolder =
                ComicTimeViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_comic_time, null))

        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: ComicTimeViewHolder?, position: Int) {
            val comic = mData[position] as ComicModel
            holder!!.mComicTitle.text = comic.title
            holder.mComicEpisodes.text = "今天更新第${comic.episodes}集"
            Glide.with(mContext).load(comic.imgUrl).centerCrop()
                    .transform(GlideRoundTransform(mContext, 4)).into(holder.mComicImage)
            holder.itemView.onClick {
                if (comic.id != null) {
                    ActivityHelper.startActivity(mContext as Activity, SingleActivity::class.java, mapOf(
                            Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_ANIME_INFO),
                            Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, comic.id)), false)
                }
            }
        }

        override fun getItemCount(): Int = mData.size
    }

    /**
     * 时间表项适配器 ViewHolder
     */
    class ComicTimeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val mComicImage: ImageView = itemView.mTimeComicImage // 新番图片
        val mComicTitle: TextView = itemView.mTimeComicTitle // 新番名
        val mComicEpisodes: TextView = itemView.mTimeComicEpisodes // 更新集数
    }
}
